package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密(把用户名作为盐)
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(),employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.insert(employee);


        if (ids != null && ids.length > 0) {
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }

    }

    @Override
    @Transactional(readOnly = true)
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);

    }

    @Override
    @Transactional(readOnly = true)
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);

        //删除原本的关系
        employeeMapper.deleteRelation(employee.getId());

        if (ids != null && ids.length > 0) {
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }


    @Override
    public PageInfo query(QueryObject qo) {
        //调用startPage方法后，会对下一句sql进行拦截，并进行改造为分页的sql
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo(employees);
    }

    @Override
    public Employee login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {     //登录失败
            throw new RuntimeException("账号密码不匹配");
        }
        return employee;
    }

    @Override
    public void updatePwd(String newPassword,String oldPassword, Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        Md5Hash md5Hash = new Md5Hash(oldPassword, employee.getName());
        oldPassword = md5Hash.toString();
        if (!(employee.getPassword().equals(oldPassword))) {
            throw new RuntimeException("原密码与旧密码不匹配");
        }
        Md5Hash md5Hash1 = new Md5Hash(newPassword,employee.getName());
        employee.setPassword(md5Hash1.toString());
        employeeMapper.updatePwdById(employee.getPassword(), id);
    }

    @Override
    public void resetPwdById(String newPassword, Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        if (!StringUtils.hasLength(newPassword)) {
            throw new RuntimeException("修改密码不能为空");
        }
        Md5Hash md5Hash = new Md5Hash(newPassword,employee.getName());
        employee.setPassword(md5Hash.toString());
        employeeMapper.resetPwdById(employee.getPassword(), id);
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    @Override
    public Workbook exportXls() {
        //创建一个表
        Workbook workbook = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = workbook.createSheet();
        //创建行
        Row row = sheet.createRow(0);
        //用行设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i <employees.size(); i++) {
            //循环遍历employees数据
            Employee employee = employees.get(i);
            //创建行，然后将循环遍历出的employee数据设置里面
            Row row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(employee.getName());
            row1.createCell(1).setCellValue(employee.getEmail());
            row1.createCell(2).setCellValue(employee.getAge());
        }
        return workbook;
    }

    @Override
    public void importxls(MultipartFile file) throws Exception {
       //将接收到的文件以excel的方式去读取
        Workbook web = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = web.getSheetAt(0);
        //获取最后一行索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读取(因为读取时索引从0开始读,所以要<=最后一行索引)
        for (int i = 1; i <=lastRowNum; i++) {
            //获取行数据,标题不用,从第一行开始读
            Row row = sheet.getRow(i);
            //通过行获取单元格数据并封装到employee对象中
            Employee employee = new Employee();
            //获取第一行name,email,age的值
            String name = row.getCell(0).getStringCellValue();
            String email = row.getCell(1).getStringCellValue();
            Integer age = Integer.valueOf( row.getCell(2).getStringCellValue());
            employee.setName(name);
            employee.setEmail(email);
            employee.setAge(age);
            employee.setPassword("1");
            employeeMapper.insert(employee);
        }


    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        List<Employee> list = employeeMapper.selectByRoleSn(sns);
           return list;
    }

    @Override
    public void updateDisableById(Long id) {
             employeeMapper.updateDisableById(id);
    }

    @Override
    public void updateRecoveryById(Long id) {
        employeeMapper.updateRecoveryById(id);
    }

}
